<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理系统</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css"> 
    <script src="./js/jquery.js"></script> 
    <script src="./js/bootstrap.min.js"></script> 
</head>
<body>
    <div class="container-fluid">
        <!-- 标题 -->
        <div class="row">
            <div class="col-md-12">
                <h1 class="text-center">商品管理系统</h1>
            </div>
        </div>
        <!-- 搜索 -->
        <div class="row"> 
            <div class="form-row col-md-4">
                <div class="col">
                <input type="text" class="form-control" placeholder="商品名称" id="productName">
                </div>
            </div>
            <div class="col-md-4">
                <button type="button" class="btn btn-primary" onclick="searchProduct()">搜索</button>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addProduct">添加</button> 
            </div>
        </div>
        <!-- 表格 -->
        <div class="row" style="margin-top: 20px;"> 
            <div class="col-md-12"> 
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th scope="col">产品ID</th>
                            <th scope="col">产品名称</th>
                            <th scope="col">类型</th>
                            <th scope="col">价格</th>
                            <th scope="col">库存</th>
                            <th scope="col">图片</th>
                            <th scope="col">状态</th>
                            <th scope="col">描述</th>
                            <th scope="col">操作</th>
                        </tr>
                    </thead>
                    <tbody id="tbody">
                    </tbody>
                </table>
            </div>
        </div>
        <!-- 新增模态框 -->
        <div class="modal fade" id="addProduct" tabindex="-1" role="dialog" aria-labelledby="addProductLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addProductLabel">新增商品</h5>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="addProductName">产品名称</label>
                            <input type="text" class="form-control" id="addProductName"/>
                        </div>
                        <div class="form-group">
                            <label for="addTypeId">类型</label>
                            <select class="form-control" id="addTypeId">
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="addPrice">价格</label>
                            <input type="number" class="form-control" id="addPrice"/>
                        </div>
                        <div class="form-group">
                            <label for="addStock">库存</label>
                            <input type="number" class="form-control" id="addStock"/>
                        </div>
                        <div class="form-group">
                            <label for="addImageUrl">图片</label>
                            <input type="file" class="form-control" id="addImageUrl"/>
                        </div>
                        <div class="form-group">
                            <label for="addStatus">状态</label>
                            <select class="form-control" id="addStatus">
                                <option value="-1">请选择</option>
                                <option value="active">上架</option>
                                <option value="inactive">下架</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="addDescription">描述</label>
                            <input type="text" class="form-control" id="addDescription"/>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="addProduct()">保存</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 编辑模态框 -->
        <div class="modal fade" id="editProduct" tabindex="-1" role="dialog" aria-labelledby="editProductLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editProductLabel">编辑商品</h5>
                    </div>
                    <div class="modal-body">
                        <div class="form-group"> 
                            <label for="editProductId">产品ID</label>
                            <input type="text" class="form-control" id="editProductId" readonly="readonly" disabled="disabled"/>
                        </div>
                        <div class="form-group">
                            <label for="editProductName">产品名称</label>
                            <input type="text" class="form-control" id="editProductName"/>
                        </div>
                        <div class="form-group">
                            <label for="editTypeId">类型</label>
                            <select class="form-control" id="editTypeId">
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editPrice">价格</label>
                            <input type="number" class="form-control" id="editPrice"/>
                        </div>
                        <div class="form-group">
                            <label for="editStock">库存</label>
                            <input type="number" class="form-control" id="editStock"/>
                        </div>
                        <div class="form-group">
                            <label for="editImageUrl">图片</label>
                            <input type="file" class="form-control" id="editImageUrl"/>
                        </div>
                        <div class="form-group">
                            <label for="editStatus">状态</label>
                            <select class="form-control" id="editStatus">
                                <option value="-1">请选择</option>
                                <option value="active">上架</option>
                                <option value="inactive">下架</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editDescription">描述</label>
                            <input type="text" class="form-control" id="editDescription"/>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="editProduct()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script>
    $(function(){
        getProductList();
        getTypeList();
    });
 
    // 获取商品列表 
    function getProductList(name){ 
        let productParam = {name: name || ''};
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:25080/product/list",
            data: JSON.stringify(productParam), 
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
                console.log(data); 
                $('#tbody').empty();
                for(const product of data){
                    let tr = `<tr>
                        <th scope="row">${product.productId}</th> 
                        <td>${product.productName}</td> 
                        <td>${product.productTypes  ? product.productTypes.typeName  : '无类型'}</td>
                        <td>${product.price}</td> 
                        <td>${product.stock}</td> 
                        <td><img src="${product.imageUrl  || ''}" width="50" height="50"></td>
                        <td>${product.status}</td> 
                        <td>${product.description  || ''}</td>
                        <td>
                            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editProduct" onclick="getProductDetail(${product.productId})"> 修改</button>
                            <button type="button" class="btn btn-danger" onclick="deleteProduct(${product.productId})"> 删除</button>
                        </td>
                    </tr>`;
                    $('#tbody').append(tr);
                }
            },
            error: function(xhr, status, error) {
                console.error(" 获取商品列表失败:", error);
            }
        });
    } 
 
    // 获取类型列表
    function getTypeList(){
        $.ajax({
            type: "GET",
            url: "http://127.0.0.1:25080/product/type/list",
            dataType: "json",
            success: function(data) {
                console.log(data); 
                // 清空下拉框 
                $("#addTypeId, #editTypeId").empty();
                // 添加默认选项
                $('#addTypeId, #editTypeId').append(`<option value="-1">请选择</option>`);
                if(data && data.length  > 0){
                    for(const productType of data){ 
                        $('#addTypeId').append(`<option value="${productType.typeId}">${productType.typeName}</option>`); 
                        $('#editTypeId').append(`<option value="${productType.typeId}">${productType.typeName}</option>`); 
                    } 
                }
            },
            error: function(xhr, status, error) {
                console.error(" 获取类型列表失败:", error);
            }
        });
    }
 
    // 添加商品
    function addProduct(){
        // 上传图片 
        let fileInput = document.getElementById('addImageUrl'); 
        if(fileInput.files.length  > 0) {
            let formData = new FormData();
            formData.append('file',  fileInput.files[0]); 
            
            $.ajax({
                url: "http://127.0.0.1:25080/product/upload",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function(imageUrl) {
                    // 图片上传成功后，添加商品 
                    saveProduct(imageUrl);
                },
                error: function() {
                    alert("图片上传失败");
                }
            });
        } else {
            // 没有上传图片，直接添加商品
            saveProduct('');
        }
    }
 
   function saveProduct(imageUrl) {
       let product = {
           productName: $('#addProductName').val(),
           typeId: $('#addTypeId').val(),
           price: parseFloat($('#addPrice').val()),
           stock: parseInt($('#addStock').val()),
           imageUrl: imageUrl || '',
           status: $('#addStatus').val(),
           description: $('#addDescription').val()
       };
    
       // 验证必填字段 
       if(!product.productName  || product.typeId  == -1) {
           alert("请填写产品名称并选择类型");
           return;
       }
    
       $.ajax({
           url: "http://127.0.0.1:25080/product/add",
           type: "POST",
           data: JSON.stringify(product), 
           contentType: "application/json",
           // 修改1：移除dataType或确保与后端一致 
           // dataType: "json", // 先注释掉 
           success: function(response, textStatus, xhr) {
               console.log(" 响应数据:", response); 
               console.log(" 状态:", textStatus);
               console.log("XHR 对象:", xhr);
               
               // 修改2：更灵活的响应处理 
               try {
                   if (typeof response === 'string') {
                       response = JSON.parse(response); 
                   }
                   
                   if(response && (response.success  || xhr.status  === 200)) {
                       alert("操作成功");
                       $('#addProduct').modal('hide');
                       getProductList();
                       clearForm();
                   } else {
                       alert(response.message  || "操作失败");
                   }
               } catch (e) {
                   alert("处理响应时出错: " + e.message); 
               }
           },
           error: function(xhr, textStatus, errorThrown) {
               console.error(" 完整错误信息:", {
                   status: xhr.status, 
                   statusText: xhr.statusText, 
                   responseText: xhr.responseText, 
                   textStatus: textStatus,
                   errorThrown: errorThrown 
               });
               
               // 修改3：更友好的错误提示 
               let errorMsg = "请求失败: ";
               try {
                   const response = JSON.parse(xhr.responseText); 
                   errorMsg += response.message  || xhr.statusText; 
               } catch (e) {
                   errorMsg += xhr.responseText  || xhr.statusText  || "未知错误";
               }
               alert(errorMsg);
           }
       });
   }
 
    // 获取商品详情
    function getProductDetail(id){ 
        $.ajax({
            type: "GET",
            url: "http://127.0.0.1:25080/product/detail?productId="+id,
            dataType: "json",
            success: function(data) {
                console.log(data); 
                $('#editProductId').val(data.productId); 
                $('#editProductName').val(data.productName); 
                $('#editTypeId').val(data.productTypes  ? data.productTypes.typeId  : -1);
                $('#editPrice').val(data.price); 
                $('#editStock').val(data.stock); 
                $('#editStatus').val(data.status); 
                $('#editDescription').val(data.description); 
                // 图片URL不在这里设置，因为它是只读的 
            },
            error: function(xhr, status, error) {
                console.error(" 获取商品详情失败:", error);
            }
        });
    }
 
    function editProduct() { 
        let productId = $('#editProductId').val();
        let productName = $('#editProductName').val();
        let typeId = $('#editTypeId').val();
        let price = parseFloat($('#editPrice').val());
        let stock = parseInt($('#editStock').val());
        let status = $('#editStatus').val();
        let description = $('#editDescription').val();
        
        let product = {
            productId: productId,
            productName: productName,
            typeId: typeId,
            price: price,
            stock: stock,
            status: status,
            description: description 
        };
        
        // 检查是否有新图片上传 
        let fileInput = document.getElementById('editImageUrl');  
        if(fileInput.files.length  > 0) {
            let formData = new FormData();
            formData.append('file',  fileInput.files[0]);  
            
            $.ajax({
                url: "http://127.0.0.1:25080/product/upload",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function(imageUrl) {
                    product.imageUrl  = imageUrl;
                    updateProduct(product);
                },
                error: function() {
                    alert("图片上传失败");
                }
            });
        } else {
            // 没有上传新图片，保留原有图片URL 
            updateProduct(product);
        }
    }
 
   function updateProduct(product) {
       $.ajax({
           url: "http://127.0.0.1:25080/product/update",
           type: "POST",
           data: JSON.stringify(product),  
           contentType: "application/json",
           dataType: "text",
           success: function(data) {
               if(data == "success"){
                   alert("修改成功");
                   $('#editProduct').modal('hide');
                   getProductList();
               } else {
                   alert("修改失败");
               }
           },
           error: function(xhr) {
               let errorMsg = "修改失败";
               if (xhr.responseJSON  && xhr.responseJSON.message)  {
                   errorMsg += ": " + xhr.responseJSON.message;  
               }
               alert(errorMsg);
           }
       });
   }
 
    // 搜索商品
    function searchProduct(){
        let name = $('#productName').val();
        getProductList(name);
    }
 
    // 清空表单
    function clearForm() {
        $('#addProductName').val('');
        $('#addTypeId').val('-1');
        $('#addPrice').val('');
        $('#addStock').val('');
        $('#addImageUrl').val('');
        $('#addStatus').val('-1');
        $('#addDescription').val('');
    }
 
    // 删除商品
    function deleteProduct(id){ 
        if(confirm('确定删除吗？')){
            $.ajax({
                type: "DELETE",
                url: "http://127.0.0.1:25080/product/delete?productId="+id,
                dataType: "text",
                success: function(data) {
                    console.log(data); 
                    if(data == "success"){
                        alert("删除成功");
                        getProductList();
                    } else {
                        alert("删除失败");
                    }
                },
                error: function(xhr, status, error) {
                    console.error(" 删除商品失败:", error);
                    alert("删除失败: " + error);
                }
            });
        }
    }
</script>